/*
 * Copyright (c) 2012 Sean Connelly
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var assert = require('../assert.js').init();
var common = require('../../src/js/common.js');
var path = require('path');
var fs = require('fs');
var txs = require('../../src/js/text-stream.js');
var lxr = require('../../src/js/lex-rho.js');
var psr = require('../../src/js/parse-rho.js');
var crMarkScopes = require('../../src/js/cr-mark-scopes.js').run;

function loadRhoFile(test_dir, file)
{
	var c = fs.readFileSync(path.resolve(test_dir, file), 'utf8');
	assert.that(file + ' loaded', c.length > 0);
	return c;
}

function loadTxtFile(test_dir, file)
{
	var c = fs.readFileSync(path.resolve(test_dir, file), 'utf8');
	assert.that(file + ' loaded', c.length > 0);
	return c.replace(/^\s+|\s+$/g, '');
}

function flattenScope(rho_obj)
{
	var out = '';
	function log_scope(sc, t)
	{
		out += common.stringRepeat('  ', t) + sc.name + '\n';
		for (var i = 0; i < sc.children.length; i++)
			log_scope(sc.children[i], t + 1);
	}
	log_scope(rho_obj.scopeTree, 0);
	return out.replace(/^\s+|\s+$/g, '');
}

function testFile(test_dir, file)
{
	var rho_obj = {
			ast: psr.parse(lxr.lex(txs.create(loadRhoFile(test_dir, file + '.rho'))))
		};
	crMarkScopes(rho_obj);
	var target = flattenScope(rho_obj);
	//fs.writeFileSync(path.resolve(test_dir, file + '.out.txt'), target, 'utf8');
	assert.that(file + ' matches target scope', target === loadTxtFile(test_dir, file + '.txt'));
}

exports.run = function(root_dir, test_dir, test_name) {
		for (var i = 1; i <= 3; i++)
			testFile(test_dir, 'test' + i);
		return assert.result();
	};
